<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文章来源" prop="articleOrigin">
        <el-input
          v-model="queryParams.articleOrigin"
          placeholder="请输入文章来源"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="责任编辑" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入责任编辑"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['article:draft:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['article:draft:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['article:draft:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['article:draft:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="draftList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文章ID" align="center" prop="articleId" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="文章来源" align="center" prop="articleOrigin" />
      <el-table-column label="栏目名称" align="center" prop="name" />
      <el-table-column label="内容" align="center" prop="content" :formatter="formatContent" />
      <el-table-column label="责任编辑" align="center" prop="author" />
      <el-table-column label="审核日期" align="center" prop="pubdate" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['article:draft:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handlePublish(scope.row)"
            v-hasPermi="['article:draft:edit']"
          >发布</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['article:draft:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改草稿文章对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="文章来源" prop="articleOrigin">
          <el-input v-model="form.articleOrigin" placeholder="请输入文章来源" />
        </el-form-item>
        <el-form-item label="栏目名称" prop="name">
          <el-select v-model="form.name" placeholder="请选择栏目名称" clearable filterable>
            <el-option
              v-for="item in columnOptions"
              :key="item.columnId"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="责任编辑" prop="author">
          <el-input v-model="form.author" placeholder="请输入责任编辑" />
        </el-form-item>
        <el-form-item label="审核日期" prop="pubdate">
          <el-date-picker clearable
            v-model="form.pubdate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择审核日期">
          </el-date-picker>
        </el-form-item>

        <!-- 审批表上传 -->
        <el-form-item label="审批表">
          <el-upload
            ref="appvalUpload"
            :file-list="appvalFileList"
            :before-upload="beforeAppvalUpload"
            :on-change="handleAppvalFileChange"
            :auto-upload="false"
            :on-remove="handleAppvalRemove"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            action="#"
            :http-request="handleAppvalHttpRequest"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传审批表图片</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">更新草稿</el-button>
        <el-button type="success" @click="handlePublishFromDialog">直接发布</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDraft, getDraft, delDraft, addDraft, updateDraft, exportDraft, publishDraft } from "@/api/draft/index";
import { listConlumnList } from "@/api/conlumn/conlumn";
import { uploadAppval, uploadContentImage } from "@/api/article/article";

export default {
  name: "Draft",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 草稿文章表格数据
      draftList: [],
      // 栏目选项
      columnOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        articleOrigin: null,
        author: null
      },
      // 表单参数
      form: {},
      // 审批表文件列表
      appvalFileList: [],
      // 待上传的审批表文件
      uploadAppvalFile: null,
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        articleOrigin: [
          { required: true, message: "文章来源不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "栏目名称不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        author: [
          { required: true, message: "责任编辑不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getColumnList();
    this.getList();
  },
  methods: {
    /** 查询栏目列表 */
    getColumnList() {
      listConlumnList().then(response => {
        this.columnOptions = response.rows;
      });
    },
    /** 查询草稿文章列表 */
    getList() {
      this.loading = true;
      listDraft(this.queryParams).then(response => {
        this.draftList = response.rows;
        // 处理栏目名称映射
        this.draftList = this.draftList.map(item => {
          const column = this.columnOptions.find(col => col.id === item.columnId);
          return {
            ...item,
            name: column ? column.name : '未知栏目',
          };
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        articleId: null,
        title: null,
        articleOrigin: null,
        columnId: null,
        content: null,
        author: null,
        pubdate: null,
        name: null,
        appval: null
      };
      this.appvalFileList = [];
      this.uploadAppvalFile = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.articleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加草稿文章";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const articleId = row.articleId || this.ids
      getDraft(articleId).then(response => {
        this.form = response.data;
        // 设置栏目名称
        const column = this.columnOptions.find(col => col.id === this.form.columnId);
        this.form.name = column ? column.name : '';

        // 初始化审批表文件列表
        if (this.form.appval) {
          this.appvalFileList = [{
            name: '审批表',
            url: this.form.appval
          }];
        } else {
          this.appvalFileList = [];
        }

        this.open = true;
        this.title = "修改草稿文章";
      });
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 设置栏目ID
          const column = this.columnOptions.find(col => col.name === this.form.name);
          if (column) {
            this.form.columnId = column.id;
          }

          // 处理审批表上传
          if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
            try {
              // 压缩审批表图片
              const compressedFile = await this.compressImage(this.uploadAppvalFile, false);
              const formData = new FormData();
              formData.append('appvalPath', compressedFile);
              const response = await uploadAppval(this.form.articleId || 0, formData);
              if (response.code === 200) {
                this.form.appval = response.url;
              }
            } catch (error) {
              console.error('审批表上传失败:', error);
              this.$message.error('审批表上传失败: ' + error.message);
              return;
            }
          }

          // 处理文章内容中的本地图片上传到OSS
          if (this.form.content) {
            try {
              // 直接使用正则表达式替换本地图片路径
              const localImageRegex = /<img[^>]*src=["'](\/dev-api\/profile\/upload\/[^"']+)["'][^>]*>/g;
              let match;
              const processedPaths = new Set();

              // 找到所有本地图片路径并上传到OSS
              while ((match = localImageRegex.exec(this.form.content)) !== null) {
                const fullImgTag = match[0];
                const localPath = match[1];

                // 避免重复处理
                if (processedPaths.has(localPath)) {
                  continue;
                }
                processedPaths.add(localPath);

                try {
                  // 获取图片并上传到OSS
                  const response = await fetch(localPath);
                  const blob = await response.blob();
                  const fileName = localPath.split('/').pop() || `content_image_${Date.now()}.jpg`;
                  const file = new File([blob], fileName, { type: blob.type });

                  // 压缩图片
                  const compressedFile = await this.compressImage(file);

                  // 上传到OSS
                  const uploadResult = await uploadContentImage(compressedFile);
                  if (uploadResult.code === 200) {
                    // 替换HTML中的路径
                    const newImgTag = fullImgTag.replace(localPath, uploadResult.url);
                    this.form.content = this.form.content.replace(new RegExp(localPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), uploadResult.url);
                    console.log(`图片路径已替换: ${localPath} -> ${uploadResult.url}`);
                  }
                } catch (uploadError) {
                  console.error('图片上传失败:', uploadError);
                }
              }
            } catch (error) {
              console.error('处理文章内容图片失败:', error);
              this.$message.warning('文章内容中的本地图片处理失败，将保存原始内容');
            }
          }

          if (this.form.articleId != null) {
            updateDraft(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDraft(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const articleIds = row.articleId || this.ids;
      this.$modal.confirm('是否确认删除草稿文章编号为"' + articleIds + '"的数据项？').then(function() {
        return delDraft(articleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('article/draft/export', {
        ...this.queryParams
      }, `draft_${new Date().getTime()}.xlsx`)
    },
    /** 发布草稿 */
    handlePublish(row) {
      this.$modal.confirm('是否确认发布该草稿？').then(() => {
        return publishDraft(row.articleId);
      }).then(() => {
        this.$modal.msgSuccess("发布成功");
        this.getList();
      }).catch(() => {
        // 用户取消操作
      });
    },
    /** 从对话框直接发布草稿 */
    handlePublishFromDialog() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 设置栏目ID
          const column = this.columnOptions.find(col => col.name === this.form.name);
          if (column) {
            this.form.columnId = column.id;
          }

          // 处理审批表上传
          if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
            try {
              // 压缩审批表图片
              const compressedFile = await this.compressImage(this.uploadAppvalFile, false);
              const formData = new FormData();
              formData.append('appvalPath', compressedFile);
              const response = await uploadAppval(this.form.articleId || 0, formData);
              if (response.code === 200) {
                this.form.appval = response.url;
              }
            } catch (error) {
              console.error('审批表上传失败:', error);
              this.$message.error('审批表上传失败: ' + error.message);
              return;
            }
          }

          // 处理文章内容中的本地图片上传到OSS
          if (this.form.content) {
            try {
              // 直接使用正则表达式替换本地图片路径
              const localImageRegex = /<img[^>]*src=["'](\/dev-api\/profile\/upload\/[^"']+)["'][^>]*>/g;
              let match;
              const processedPaths = new Set();

              // 找到所有本地图片路径并上传到OSS
              while ((match = localImageRegex.exec(this.form.content)) !== null) {
                const fullImgTag = match[0];
                const localPath = match[1];

                // 避免重复处理
                if (processedPaths.has(localPath)) {
                  continue;
                }
                processedPaths.add(localPath);

                try {
                  // 获取图片并上传到OSS
                  const response = await fetch(localPath);
                  const blob = await response.blob();
                  const fileName = localPath.split('/').pop() || `content_image_${Date.now()}.jpg`;
                  const file = new File([blob], fileName, { type: blob.type });

                  // 压缩图片
                  const compressedFile = await this.compressImage(file);

                  // 上传到OSS
                  const uploadResult = await uploadContentImage(compressedFile);
                  if (uploadResult.code === 200) {
                    // 替换HTML中的路径
                    const newImgTag = fullImgTag.replace(localPath, uploadResult.url);
                    this.form.content = this.form.content.replace(new RegExp(localPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), uploadResult.url);
                    console.log(`图片路径已替换: ${localPath} -> ${uploadResult.url}`);
                  }
                } catch (uploadError) {
                  console.error('图片上传失败:', uploadError);
                }
              }
            } catch (error) {
              console.error('处理文章内容图片失败:', error);
              this.$message.warning('文章内容中的本地图片处理失败，将保存原始内容');
            }
          }

          // 先保存草稿再发布
          if (this.form.articleId != null) {
            updateDraft(this.form).then(response => {
              // 发布草稿
              return publishDraft(this.form.articleId);
            }).then(() => {
              this.$modal.msgSuccess("发布成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              this.$modal.msgError("发布失败: " + error.message);
            });
          } else {
            addDraft(this.form).then(response => {
              // 发布草稿
              return publishDraft(response.articleId || this.form.articleId);
            }).then(() => {
              this.$modal.msgSuccess("发布成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              this.$modal.msgError("发布失败: " + error.message);
            });
          }
        }
      });
    },
    /** 格式化内容显示 */
    formatContent(row, column, cellValue) {
      // 移除HTML标签并截取前100个字符
      const plainText = cellValue ? cellValue.replace(/<[^>]*>/g, '') : '';
      return plainText.length > 100 ? plainText.substring(0, 100) + '...' : plainText;
    },

    // 审批表上传请求处理
    async handleAppvalHttpRequest(options) {
      try {
        const formData = new FormData();
        formData.append('appvalPath', options.file);

        const response = await uploadAppval(this.form.articleId || 0, formData);
        if (response.code === 200) {
          this.form.appval = response.url;
          this.$message.success('审批表上传成功');
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('审批表上传失败:', error);
        this.$message.error('审批表上传失败: ' + error.message);
      }
    },

    // 审批表文件上传前处理
    beforeAppvalUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('图片大小不能超过10M!');
        return false;
      }

      this.uploadAppvalFile = file;
      return false; // 阻止自动上传
    },

    // 审批表文件变化处理
    handleAppvalFileChange(file, fileList) {
      if (fileList.length > 0) {
        this.uploadAppvalFile = fileList[0].raw;
        this.appvalFileList = [fileList[fileList.length - 1]]; // 只保留最后一个文件
      } else {
        this.uploadAppvalFile = null;
        this.appvalFileList = [];
      }
    },

    // 审批表文件移除处理
    handleAppvalRemove() {
      this.uploadAppvalFile = null;
      this.form.appval = null;
      this.appvalFileList = [];
    },

    // 使用 Canvas 进行图片压缩，可以更精确地控制文件大小
    async compressImage(file, checkMinSize = true) {
      const minSizeBytes = 1024 * 1024; // 1MB 下限
      const maxSizeBytes = 5 * 1024 * 1024; // 5MB 上限
      const skipCompressSizeBytes = 3 * 1024 * 1024; // 3MB

      // 检查文件是否小于最小大小（仅当checkMinSize为true时检查）
      if (checkMinSize && file.size < minSizeBytes) {
        throw new Error('图片大小不能小于1MB!');
      }

      // 如果文件小于 3MB，直接跳过压缩
      if (file.size < skipCompressSizeBytes) {
        console.log(`文件大小为 ${file.size} bytes，小于 3MB，跳过压缩`);
        return file;
      }

      // 所有图片都使用 Canvas 进行精确压缩，确保不会低于下限
      return await this.canvasCompress(file, minSizeBytes, maxSizeBytes);
    },

    // 使用 Canvas 进行精确压缩
    async canvasCompress(file, minSizeBytes, maxSizeBytes) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();

        img.onload = async () => {
          // 初始宽高
          let width = img.width;
          let height = img.height;

          // 计算缩放比例
          const ratio = width / height;

          // 如果图片很大，先进行初步缩放
          if (width > 2048 || height > 2048) {
            if (width > height) {
              width = 2048;
              height = 2048 / ratio;
            } else {
              height = 2048;
              width = 2048 * ratio;
            }
          }

          // 设置 canvas 尺寸
          canvas.width = width;
          canvas.height = height;

          // 绘制图片到 canvas
          ctx.drawImage(img, 0, 0, width, height);

          // 二分法查找合适的质量参数
          let quality = 1;
          let minQuality = 0.1;
          let maxQuality = 2;
          let attempts = 0;
          const maxAttempts = 10;

          let compressedBlob;

          while (attempts < maxAttempts) {
            attempts++;

            // 导出为 Blob
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', quality);
            });

            console.log(`第 ${attempts} 次压缩尝试，质量: ${quality}, 大小: ${compressedBlob.size} bytes`);

            // 检查大小是否符合要求
            if (compressedBlob.size >= minSizeBytes && compressedBlob.size <= maxSizeBytes) {
              console.log('压缩成功，大小符合要求');
              break;
            }

            // 调整质量参数
            if (compressedBlob.size > maxSizeBytes) {
              // 太大了，降低质量
              maxQuality = quality;
              quality = (minQuality + quality) / 2;
            } else {
              // 太小了，提高质量
              minQuality = quality;
              quality = (quality + maxQuality) / 2;
            }

            // 如果质量调整过小，可能无法达到最小大小要求
            if (quality < 0.01) {
              console.warn('质量参数过低，无法达到最小大小要求');
              break;
            }
          }

          // 如果最终结果还是太小，使用最小质量重新压缩
          if (compressedBlob.size < minSizeBytes) {
            console.warn(`压缩后文件过小 (${compressedBlob.size} bytes)，使用最小质量重新压缩`);
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', 0.95);
            });
          }

          // 转换为 File 对象
          const compressedFile = new File([compressedBlob], file.name, {
            type: 'image/jpeg',
            lastModified: Date.now()
          });

          console.log(`最终压缩结果: ${compressedFile.size} bytes`);
          resolve(compressedFile);
        };

        img.onerror = () => {
          reject(new Error('图片加载失败'));
        };

        // 读取文件
        const reader = new FileReader();
        reader.onload = e => {
          img.src = e.target.result;
        };
        reader.onerror = () => {
          reject(new Error('文件读取失败'));
        };
        reader.readAsDataURL(file);
      });
    }
  }
};
</script>